package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiduProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper  orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil  weChatPayUtil;
    @Autowired
    private BaiduProperties  baiduProperties;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 判断地址和购物车数据是否为空 - 防止恶意调用
            //地址
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
            //购物车
        Long userId = BaseContext.getCurrentId();
        ShoppingCart  shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.isEmpty()){
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 判断商户与客户之间的距离-若超出5km则报异常
        IsOverd(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        // 新增订单
        Orders orders =new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.insert(orders);
        // 新增订单详情-批量
        List<OrderDetail> orderDetails = new ArrayList<>();

        for (ShoppingCart cart : list) {
            OrderDetail  orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetails);
        // 购物车清空
        ShoppingCart shoppingCart2 = new ShoppingCart();
        shoppingCart2.setUserId(userId);
        shoppingCartMapper.delete(shoppingCart2);
        // 返回vo
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 判断商户与客户之间的距离-若超出5km则报异常
     */

    private void IsOverd(String Useraddress) {
        String url="https://api.map.baidu.com/geocoding/v3";
        Map parpams =new HashMap<>();
        parpams.put("address", baiduProperties.getAddress());
        parpams.put("ak", baiduProperties.getAk());
        parpams.put("output", "json");
        String response = HttpClientUtil.doGet(url, parpams);
        // 判断响应结果
        JSONObject  jsonObject = JSONObject.parseObject(response);
        if (!Objects.equals(jsonObject.getString("status"), "0")){
            throw new OrderBusinessException("收货地址解析失败");
        }
        // 解析数据- 获取经纬度坐标
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lng = location.getString("lng");
        String lat = location.getString("lat");
        BigDecimal lng1 = new BigDecimal(lng);
        BigDecimal lat1 = new BigDecimal(lat);
        lng1=lng1.setScale(6, BigDecimal.ROUND_HALF_UP);
        lat1=lat1.setScale(6, BigDecimal.ROUND_HALF_UP);
        String shopLngLat = lat1 + "," + lng1;
        System.out.println("商家经纬度 "+shopLngLat);

//        获取用户的经纬度坐标
        parpams.put("address", Useraddress);
        String response2 = HttpClientUtil.doGet(url, parpams);
        // 判断响应结果
        JSONObject jsonObject2 = JSONObject.parseObject(response2);
        if (!Objects.equals(jsonObject2.getString("status"), "0")){
            throw new OrderBusinessException("收货地址解析失败");
        }
        // 解析数据- 获取用户经纬度坐标
        JSONObject location2 = jsonObject2.getJSONObject("result").getJSONObject("location");
        BigDecimal lng2 = new BigDecimal(location2.getString("lng"));
        BigDecimal lat2 = new BigDecimal(location2.getString("lat"));
        lng2=lng2.setScale(6, BigDecimal.ROUND_HALF_UP);
        lat2=lat2.setScale(6, BigDecimal.ROUND_HALF_UP);
        String  UserLngLat = lat2 + "," + lng2;
        System.out.println("用户经纬度 "+UserLngLat);

        // 路线规划 -获取距离
        String url2 = "https://api.map.baidu.com/directionlite/v1/driving";
        parpams.put("origin",shopLngLat);
        parpams.put("destination",UserLngLat);
        parpams.put("steps_info","0");
        String response3 = HttpClientUtil.doGet(url2, parpams);
        JSONObject jsonObject3 = JSONObject.parseObject(response3);
        if (!Objects.equals(jsonObject3.getString("status"), "0")){
            throw new OrderBusinessException("路线规划异常");
        }
        JSONObject route1 = jsonObject3.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        String distance = route1.getString("distance");
        System.out.println("运送距离"+distance);
        if (Integer.parseInt(distance) > 5000){
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id 获取openid
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单 - 生成数据返回给前端吊起支付
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
            OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
            vo.setPackageStr(jsonObject.getString("package"));
        }*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        //支付成功的操作
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        // 调用webSocketServer发送消息给客户端 来单提醒
        Map map = new HashMap();
        map.put("type", 1);//1代表来单提醒,2代表客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult pageQueryHistory(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 查询历史订单 -分页查询
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQueryHistory(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        // 查询订单详情
        if (page != null && !page.isEmpty()) {
            for (Orders order : page) {
                OrderVO orderVO = new OrderVO();
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                orderVOList.add(orderVO);
            }

            return new PageResult(page.getTotal(), orderVOList);
        }
        return new PageResult(0, null);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public OrderVO getOrderDetailsById(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        OrderVO  orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        // 查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    public void cancel(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException("订单已派送，请与商家联系");
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            /*weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额
*/
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    public void repetition(Long id) {
      // 将原来的订单重新加入购物车
        // 1. 查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart= new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        // 2. 将订单详情数据批量插入购物车表
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 管理端查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult AdminPageQueryOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 查询历史订单 -分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQueryHistory(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        // 查询订单详情
        if (page != null && !page.isEmpty()) {
            for (Orders order : page) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());
                String orderDishes = orderDetailList.stream().map(orderDetail -> orderDetail.getName() + "*" +
                        orderDetail.getNumber()).collect(Collectors.joining(","));
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }

            return new PageResult(page.getTotal(), orderVOList);
        }
        throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
    }

    /**
     * 各个状态订单统计
     * @return
     */
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed =0;
        Integer confirmed =0;
        Integer deliveryInProgress =0;
        List<Orders> list = orderMapper.list();
        // 遍历订单集合，根据状态进行计数
        for (Orders orders : list) {
            Integer status = orders.getStatus();
            if (status == Orders.TO_BE_CONFIRMED) {
                toBeConfirmed++;
            } else if (status == Orders.CONFIRMED) {
                confirmed++;
            } else if (status == Orders.DELIVERY_IN_PROGRESS) {
                deliveryInProgress++;
            }
        }
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }
    /**
     * 接单
     * @param ordersConfirmDTO
     */
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException("处于待接单状态才可以拒单");
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            /*String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/

            // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
            Orders orders = new Orders();
            orders.setId(ordersDB.getId());
            orders.setStatus(Orders.CANCELLED);
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);

        }
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    public void cancelAdmin(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            /*String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);*/
        }
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException("已接单的订单才能执行此操作");
        }
        Orders  orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException("派送中的订单才能执行此操作");
        }
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 催单
     * @param id
     */
    public void reminderOrder(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException("派送中的订单才能执行此操作");
        }
        Map map = new HashMap();
        map.put("orderId", ordersDB.getId());
        map.put("type",2); // 1表示来单提醒 2表示催单
        map.put("content", "订单号：" + ordersDB.getNumber());
        // 通过websocket向客户端推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }
}
